package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.entity.Mould;
import cn.stylefeng.guns.sys.modular.system.entity.MouldBoard;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.mapper.MouldBoardMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.MouldMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.RoleMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.MouldParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author jiangge
 * @since 2020-09-11
 */
@Service
public class MouldService extends ServiceImpl<MouldMapper, Mould> {
    @Resource
    private MouldBoardMapper mouldBoardMapper;

    @Resource
    private RoleMapper roleMapper;

    public LayuiPageInfo findPageBySpec(MouldParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(Mould mould) {

        StringBuilder roleNameBulider = new StringBuilder();
        if (StringUtils.isNotEmpty(mould.getRoleId())) {
            String[] roleIds = mould.getRoleId().split(",");
            Role role = null;
            for (int i=0;i<roleIds.length;i++) {
                String roleId=roleIds[i];
                role = roleMapper.selectById(Long.valueOf(roleId));
                if(i == (roleIds.length - 1)){
                    roleNameBulider.append(role.getName());
                }else {
                    roleNameBulider.append(role.getName()).append(",");
                }
            }
        }

        mould.setRoleName(roleNameBulider.toString());
        this.baseMapper.insert(mould);
        MouldBoard mouldBoard = new MouldBoard();
        mouldBoard.setPid(0L);
        mouldBoard.setPids("[0],");
        mouldBoard.setMouldId(mould.getId());
        mouldBoard.setSimpleName(mould.getTitle());
        mouldBoard.setFullName(mould.getTitle());
        mouldBoardMapper.insert(mouldBoard);
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }


}
